<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <link rel="shortcut icon" href="bootstrap/images/favicon_1.ico">
    <title>用户</title>
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="bootstrap/css/core.css" rel="stylesheet" type="text/css">
    <link href="bootstrap/css/icons.css" rel="stylesheet" type="text/css">
    <link href="bootstrap/css/components.css" rel="stylesheet" type="text/css">
    <link href="bootstrap/css/pages.css" rel="stylesheet" type="text/css">
    <link href="bootstrap/css/menu.css" rel="stylesheet" type="text/css">
    <link href="bootstrap/css/responsive.css" rel="stylesheet" type="text/css">

    <script src="bootstrap/js/modernizr.min.js"></script>

    <!-- bootstrap table css -->
    <link href="bootstrap/table/bootstrap-table.min.css" rel="stylesheet" type="text/css">
</head>
<body class="fixed-left">

<!-- Begin page -->
<div id="wrapper">

    <!-- Top Bar Start -->
    <div th:replace="~{fragment :: topbar_menu}">
    </div>
    <!-- Top Bar End -->


    <!-- ========== Left Sidebar Start ========== -->
    <div th:replace="~{fragment :: leftbar_menu(10)}">
    </div>
    <!-- Left Sidebar End -->


    <!-- ============================================================== -->
    <!-- Start right Content here -->
    <!-- ============================================================== -->
    <div class="content-page">
        <!-- Start content -->
        <div class="content">
            <div class="container">

                <!-- Page-Title -->
                <div class="row">
                    <div class="col-sm-12">
                        <div class="col-sm-5 col-md-offset-3">
                            <div class="alert alert-success alert-dismissible hidden" role="alert" ><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                <strong>成功!</strong> <label id="success_msg">Better check yourself, you're not looking too good.</label></div>
                            <div class="alert alert-danger alert-dismissible hidden" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                <strong>错误!</strong><label id="error_msg">Better check yourself, you're not looking too good.</label></div>
                        </div>

                        <ol class="breadcrumb pull-right">
                            <li>
                                <a href="#">OCP</a>
                            </li>
                            <li class="active">用户管理</li>
                        </ol>
                    </div>
                </div>
                <!--<div class="alert alert-success alert-dismissible hidden" role="alert" ><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <strong>成功!</strong> <label id="success_msg">Better check yourself, you're not looking too good.</label></div>-->

                <form class="form-inline" id="search_form" style="margin-bottom: 20px">
                    <div class="form-group">
                        <label for="username">用户名:</label>
                        <input type="username" name="username" class="form-control" id="username" placeholder="用户名">
                    </div>
                    <div class="form-group">
                        <label for="Email"> 邮箱:</label>
                        <input type="Email" name="email" class="form-control" id="Email" placeholder="Email">
                    </div>
                    <div class="form-group">
                        <label for="telephone"> 电话:</label>
                        <input type="telephone" name="telephone" class="form-control" id="telephone" placeholder="联系方式">
                    </div>

                    <button onclick="user_search()" type="button" class="btn btn-primary">查询</button>
                </form>


                <div class="row">
                    <div class="col-md-12">
                        <div class="panel panel-default">
                            <div class="panel-heading">
                                <h3 class="panel-title">用户列表
                                    <div class="muted pull-right">
                                        <button type="button" onclick="deleteBatch()" id="deleteBatch" class="me_btn_addUser btn btn-danger" data-toggle="modal"
                                                data-target="#out_user_model"> <span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>批量删除
                                        </button>
                                    </div>
                                </h3>
                            </div>
                            <div id="toolbar" class="select">
                                <select class="form-control">
                                    <option value="">Export Basic</option>
                                    <option value="all">Export All</option>
                                    <option value="selected">Export Selected</option>
                                </select>
                            </div>
                            <div class="panel-body" style="margin-top: -23px;">
                                <div class="row">
                                    <table id="userTable"
                                           data-show-export="true"
                                           data-toolbar="#toolbar"
                                           data-show-toggle="true"
                                           data-show-columns="true"></table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div> <!-- End Row -->
            </div> <!-- container -->

        </div> <!-- content -->

        <footer class="footer text-right">
            2015 © OCP.
        </footer>

    </div>
    <!-- ============================================================== -->
    <!-- End Right content here -->
    <!-- ============================================================== -->

</div>
<!-- END wrapper -->

<div th:replace="~{fragment :: #query_user_model}"></div>
<div th:replace="~{fragment :: #update_user_model}"></div>
<div th:replace="~{fragment :: #delete_user_model}"></div>
<script>
    var resizefunc = [];
</script>

<!-- jQuery  -->
<script src="bootstrap/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="bootstrap/js/detect.js"></script>
<script src="bootstrap/js/fastclick.js"></script>
<script src="bootstrap/js/jquery.slimscroll.js"></script>
<script src="bootstrap/js/jquery.blockUI.js"></script>
<script src="bootstrap/js/waves.js"></script>
<script src="bootstrap/js/wow.min.js"></script>
<script src="bootstrap/js/jquery.nicescroll.js"></script>
<script src="bootstrap/js/jquery.scrollTo.min.js"></script>

<script src="bootstrap/js/jquery.app.js"></script>

<!-- bootstrap table js -->
<!--<script src="bootstrap/table/tableExport.min.js"></script>
<script src="bootstrap/table/libs/jsPDF/jspdf.min.js"></script>
<script src="bootstrap/table/libs/jsPDF-AutoTable/jspdf.plugin.autotable.js"></script>
<script src="bootstrap/table/bootstrap-table.min.js"></script>
<script src="https://unpkg.com/bootstrap-table@1.18.0/dist/extensions/export/bootstrap-table-export.min.js"></script>-->
<script src="https://unpkg.com/tableexport.jquery.plugin/tableExport.min.js"></script>
<script src="https://unpkg.com/tableexport.jquery.plugin/libs/jsPDF/jspdf.min.js"></script>
<script src="https://unpkg.com/tableexport.jquery.plugin/libs/jsPDF-AutoTable/jspdf.plugin.autotable.js"></script>
<script src="https://unpkg.com/bootstrap-table@1.18.0/dist/bootstrap-table.min.js"></script>
<script src="bootstrap/table/bootstrap-table-zh-CN.min.js"></script>
<script src="https://unpkg.com/bootstrap-table@1.18.0/dist/extensions/export/bootstrap-table-export.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-validator/0.5.3/js/bootstrapValidator.js"></script>
<script>
    var form = $("#updateUserFrom")
    $(document).ready(function () {

        form.bootstrapValidator({
            message: '输入值不合法',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                username: {
                    message: '用户名不合法',
                    validators: {
                        notEmpty: {
                            message: '产品名不能为空'
                        },
                        stringLength: {
                            min: 3,
                            max: 30,
                            message: '请输入3到30个字符'
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9_\. \u4e00-\u9fa5 ]+$/,
                            message: '用户名只能由字母、数字、点、下划线和汉字组成 '
                        }
                    }
                },
                password: {
                    message: '密码不合法',
                    validators: {
                        notEmpty: {
                            message: '密码不能为空'
                        },
                        stringLength: {
                            min: 6,
                            max: 30,
                            message: '请输入3到30个字符'
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9_\. \u4e00-\u9fa5 ]+$/,
                            message: '密码只能由字母、数字、点、下划线和汉字组成 '
                        }
                    }
                }
                ,  age: {
                    validators: {
                        notEmpty: {
                            message: '年龄不能为空'
                        },
                        digits:{
                            message: "只允许输入数字"
                        },
                        greaterThan:{
                            value:1,
                            message: "年龄不能小于1"
                        },
                        lessThan:{
                            value:199,
                            message: "年龄不能大于199"
                        },
                    }
                }, price: {
                    validators: {
                        notEmpty: {
                            message: '单价不能为空'
                        },
                        regexp: {
                            regexp: /^\d+(\.\d+)?$/,
                            message: "只能输入数字字符"
                        }
                    }
                }, email: {
                    validators: {
                        notEmpty: {
                            message: '邮箱不能为空'
                        }, emailAddress:{
                            message: '邮箱地址不正确。'
                        }
                    }
                },telephone: {
                    validators: {
                        notEmpty: {
                            message: '电话不能为空'
                        },digits:{
                            message: "只允许输入数字"
                        },
                        regexp:{
                            regexp: /^1[3456789]\d{9}$/,
                            message: "电话号码格式不正确"
                        }
                    }
                }
            }
        });
    });
    $(function () {
        $('#toolbar').find('select').change(function () {
            $('#userTable').bootstrapTable('destroy').bootstrapTable({
                url: '/user/getUsers',
                striped: true,                      //是否显示行间隔色
                method: 'get',
                cache: false,
                pagination: true,
                pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
                pageSize: 10,                     //每页的记录行数（*）
                paginationLoop: false, //设置为 true 启用分页条无限循环的功能。
                pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
                sidePagination: 'server',
                clickToSelect: true,
                uniqueId: "id",
                exportTypes: ['json', 'xml', 'csv', 'txt', 'sql', 'excel', 'pdf'],
                exportOptions: {
                    fileName: function () {
                        return 'userTable'
                    }
                },
                columns: [
                    {checkbox: true, visible: true},                          //是否显示复选框
                    {field: 'id', title: '用户编号'},
                    {field: 'username', title: '用户姓名'},
                    // {field: 'password', title: '用户密码'},
                    {field: 'gender', title: '性别', formatter: function (value) { return (value==0)?'男':'女'  }},
                    {field: 'age', title: '年龄'},
                    {field: 'email', title: '邮箱'},
                    {field: 'telephone', title: '联系方式'},
                    {field: 'state', title: '权限',formatter: function (value) { return (value==0)?'管理员':'普通用户'  }},
                    {
                        title: '操作',
                        formatter: function (value, row, index) {
                            return '<a><button type="button" onclick="userInfo(' + row.id + ')" class="btn btn-success" data-toggle="modal" data-target="#query_user_model"><span class="glyphicon glyphicon-search"></span>详情</button></a>&nbsp;&nbsp;' +
                                '<a><button type="button" onclick="userUpdate(' + row.id + ')" class="btn btn-warning" data-toggle="modal" data-target="#update_user_model"><span class="glyphicon glyphicon-pencil"></span>编辑</button></a>&nbsp;&nbsp;' +
                                '<a><button type="button" onclick="userDelete(' + row.id + ')" class="btn btn-danger" data-toggle="modal" data-target="#delete_user_model"><span class="glyphicon glyphicon-remove"></span>删除</button></a>';
                        }
                    }
                ],
                queryParams: function (params) {
                    //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
                    params = {
                        pageSize: params.limit,                         //页面大小
                        pageNum: (params.offset / params.limit) + 1,   //页码
                    };
                    return params;
                }
            });
        }).trigger('change')
    });

    // 点击批量删除
    function deleteBatch() {
        let pageNum = $('#userTable').bootstrapTable("getOptions").pageNumber
        let pageSize = $('#userTable').bootstrapTable("getOptions").pageSize
        var rows = $("#userTable").bootstrapTable('getSelections');
        if (rows.length == 0) {// rows 主要是为了判断是否选中，下面的else内容才是主要
            alert("请先选择要删除的记录!");
            return;
        } else {
            var arrays = new Array();// 声明一个数组
            $(rows).each(function () {// 通过获得别选中的来进行遍历
                arrays.push(this.id);// cid为获得到的整条数据中的一列
            });
            var idcard = arrays.join(','); // 获得要删除的id
            console.log(idcard);
            if (window.confirm ("你确定真的要删除id为" + idcard + "的用户信息吗")){

            }else{
                return ;
            }
            $.ajax({
                url: "/user/deleteBatch",
                data: {ids:idcard,pageNum:pageNum,pageSize:pageSize},
                type: "GET",
                success: function (result) {
                    console.log(result)
                    if (result.code == 1){
                        $("#success_msg").parent().removeClass("hidden")
                        $("#success_msg").text(result.msg)
                        setTimeout(function (){
                            $("#success_msg").parent().addClass("hidden")
                        },1500)
                    }else{
                        $("#error_msg").parent().removeClass("hidden")
                        $("#error_msg").text(result.msg)
                        setTimeout(function (){
                            $("#error_msg").parent().addClass("hidden")
                        },1500)
                        return;
                    }
                    $("#userTable").bootstrapTable('load', result.result);
                }
            })
        }
    }

    // 点击详情按钮 ajax传值
    function userInfo(id) {
        console.log(id)
        $.ajax({
            url: "/user/getUser/" + id,
            method: "GET",
            datatype: "JSON",
            success: function (result) {
                console.log(result)
                let uid = result.id;
                let uname = result.username;
                let upassword = result.password;
                let uage = result.age;
                let utelephone = result.telephone;
                let uemail = result.email;
                $("#user_id").val(uid)
                $("#user_name").val(uname)
                $("#user_password").val(upassword)
                $("#query_user_model input[name=gender]").val([result.gender])
                $("#user_age").val(uage)
                $("#user_telephone").val(utelephone)
                $("#user_email").val(uemail)
            }
        })
    }

    // 点击编辑按钮 ajax传值
    function userUpdate(id) {
        let pageNum = $('#userTable').bootstrapTable("getOptions").pageNumber
        console.log(pageNum)
        $.ajax({
            url: "/user/getUser/" + id,
            method: "GET",
            datatype: "JSON",
            success: function (result) {
                console.log(result)
                let uid = result.id;
                let uname = result.username;
                let upassword = result.password;
                let uage = result.age;
                let utelephone = result.telephone;
                let uemail = result.email;
                $("#edit_user_id").val(uid)
                $("#edit_user_hidden_id").val(uid)
                $("#edit_user_name").val(uname)
                $("#edit_user_password").val(upassword)
                $("#edit_user_age").val(uage)
                $("#update_user_model input[name=gender]").val([result.gender])
                $("#edit_user_telephone").val(utelephone)
                $("#edit_user_email").val(uemail)

            }
        })
    }

    // 点击删除按钮 ajax传值
    function userDelete(id) {
        $("#user_delete").attr("userid", id)
        $("#user_del_modelbody").text("确定删除id为" + id + "的用户吗？")
    }

    // 点击确认删除 ajax刷新表格
    function user_delete_confirm(data) {
        let uid = $(data).attr("userid");
        let pageNum = $('#userTable').bootstrapTable("getOptions").pageNumber
        let pageSize = $('#userTable').bootstrapTable("getOptions").pageSize
        console.log(uid)
        $.ajax({
            url: "/user/deleteUser/" + uid,
            data: {pageNum: pageNum, pageSize: pageSize},
            type: "DELETE",
            success: function (result) {
                console.log(result)
                if (result.code == 1){
                    $("#success_msg").parent().removeClass("hidden")
                    $("#success_msg").text(result.msg)
                    setTimeout(function (){
                        $("#success_msg").parent().addClass("hidden")
                    },1500)
                }else{
                    $("#error_msg").parent().removeClass("hidden")
                    $("#error_msg").text(result.msg)
                    setTimeout(function (){
                        $("#error_msg").parent().addClass("hidden")
                    },1500)
                    return;
                }
                $("#userTable").bootstrapTable('load', result.result);
                $("#delete_user_model").modal('toggle')
            }
        })
    }
    // 点击模态框的修改按钮 ajax刷新表格
    function updateUserForm() {
        let bv = form.data('bootstrapValidator');
        bv.validate();
        if (bv.isValid()) {
            let user = $("#updateUserFrom").serialize();
            //获取当前页
            let pageNum = $('#userTable').bootstrapTable("getOptions").pageNumber
            let pageSize = $('#userTable').bootstrapTable("getOptions").pageSize
            $.ajax({
                url: "/user/setUser?" + user,
                type: "PUT",
                data: {pageNum: pageNum, pageSize: pageSize},
                dataType: "JSON",
                success: function (result) {
                    if (result.code == 1){
                        $("#success_msg").parent().removeClass("hidden")
                        $("#success_msg").text(result.msg)
                        setTimeout(function (){
                            $("#success_msg").parent().addClass("hidden")
                        },1500)
                    }else{
                        $("#error_msg").parent().removeClass("hidden")
                        $("#error_msg").text(result.msg)
                        setTimeout(function (){
                            $("#error_msg").parent().addClass("hidden")
                        },1500)
                        return;
                    }
                    console.log(result)
                    $("#userTable").bootstrapTable('load', result.result);
                    $("#update_user_model").modal('toggle')
                }
            })
        }
    }

    // 模糊查询 提交
    function user_search() {
        var searchUser = $("#search_form").serialize();
        console.log(searchUser)
        $('#toolbar').find('select').change(function () {
            $('#userTable').bootstrapTable('destroy').bootstrapTable({
                url: '/user/search?' + searchUser,
                striped: true,                      //是否显示行间隔色
                method: 'get',
                cache: false,
                pagination: true,
                pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
                pageSize: 10,                     //每页的记录行数（*）
                paginationLoop: false, //设置为 true 启用分页条无限循环的功能。
                pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
                sidePagination: 'server',
                clickToSelect: true,
                uniqueId: "id",
                exportTypes: ['json', 'xml', 'csv', 'txt', 'sql', 'excel', 'pdf'],
                exportOptions: {
                    fileName: function () {
                        return 'userTable'
                    }
                },
                columns: [
                    {checkbox: true, visible: true},                          //是否显示复选框
                    {field: 'id', title: '用户编号'},
                    {field: 'username', title: '用户姓名'},
                    // {field: 'password', title: '用户密码'},
                    {field: 'gender', title: '性别', formatter: function (value) { return (value==0)?'男':'女'  }},
                    {field: 'age', title: '年龄'},
                    {field: 'email', title: '邮箱'},
                    {field: 'telephone', title: '联系方式'},
                    {field: 'state', title: '权限',formatter: function (value) { return (value==0)?'管理员':'普通用户'  }},
                    {
                        title: '操作',
                        formatter: function (value, row, index) {
                            return '<a><button type="button" onclick="userInfo(' + row.id + ')" class="btn btn-success" data-toggle="modal" data-target="#query_user_model"><span class="glyphicon glyphicon-search"></span>详情</button></a>&nbsp;&nbsp;' +
                                    '<a><button type="button" onclick="userUpdate(' + row.id + ')" class="btn btn-warning" data-toggle="modal" data-target="#update_user_model"><span class="glyphicon glyphicon-pencil"></span>编辑</button></a>&nbsp;&nbsp;' +
                                    '<a><button type="button" onclick="userDelete(' + row.id + ')" class="btn btn-danger" data-toggle="modal" data-target="#delete_user_model"><span class="glyphicon glyphicon-remove"></span>删除</button></a>';
                        }
                    }
                ],
                queryParams: function (params) {
                    //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
                    params = {
                        pageSize: params.limit,                         //页面大小
                        pageNum: (params.offset / params.limit) + 1,   //页码
                    };
                    return params;
                }
            });
        }).trigger('change')
    }
</script>

</body>
</html>